package cn.algorithms_4ed.algo.sort;

import cn.stdlib.StdOut;
import cn.stdlib.StdRandom;

/**
 * Sort compare
 * <p/>
 * User: erhu
 * Date: 13-6-15
 * Time: 下午12:38
 */
public class SortCompare {

    public static long time(Sort algorithm) {
        long begin = System.currentTimeMillis();
        algorithm.sort();
        return System.currentTimeMillis() - begin;
    }

    /**
     * 使用算法将T个长度为N的数组排序
     *
     * @param algorithm  算法
     * @param dataLength 数组长度
     * @param dataGroup  数组个数
     * @return 总时间
     */
    public static double timeRandomInput(Sort algorithm, int dataLength, int dataGroup) {
        double total = 0.0;
        Double[] data = new Double[dataLength];

        for (int t = 0; t < dataGroup; t++) {
            for (int i = 0; i < dataLength; i++) {
                data[i] = StdRandom.uniform();
            }
            algorithm.setData(data);
            long t_time = time(algorithm);
            total += t_time;
        }
        StdOut.printf("%10s cost %.2f ms \n", algorithm, total);
        return total;
    }

    public static void main(String[] args) {
        Sort algo_insert = new Insertion();
        Sort algo_selection = new Selection();
        Sort algo_shell = new Shell();
        Sort algo_merge = new Merge();
        Sort algo_quick = new Quick();


        int data_length = 300000;
        int data_group = 100;
        printResult(algo_quick, algo_shell, data_length, data_group);
    }

    private static void printResult(Sort algo_fast, Sort algo_slow, int dataLength, int dataGroup) {
        double time_short = timeRandomInput(algo_fast, dataLength, dataGroup);
        double time_long = timeRandomInput(algo_slow, dataLength, dataGroup);

        StdOut.printf("\n------------------------------------------------\n");
        StdOut.printf("For %d random Doubles \n%s is ", dataLength, algo_fast);
        StdOut.printf("%.1f times faster than %s \n\n", time_long / time_short, algo_slow);
    }
}
